let finalPatch = {},
  rnIndex = 0;

import { ATTR, TEXT, REMOVE, REPLACE } from "./patchType";
import { setAttrs, render } from "./vitureDom";
import Element from "./element";

function doPatch(rDom, patches) {
  finalPatch = patches;
  rNodeWalk(rDom);
}

function rNodeWalk(rNode) {
  const rnPatch = finalPatch[rnIndex++],
    childNodes = rNode.childNodes;
  [...childNodes].map((c) => {
    rNodeWalk(c);
  });

  if (rnPatch) {
    patchAction(rNode, rnPatch);
  }
}

function patchAction(rNode, rnPatch) {
  rnPatch.map((p) => {
    switch (p.type) {
      case ATTR:
        for (let key in p.attrs) {
          const value = p.attrs[key];
          if (value) {
            setAttrs(rNode, key, value);
          } else {
            rNode.removeAttribute(key);
          }
        }
        break;
      case TEXT:
        rNode.textContent = p.text;
        break;
      case REMOVE:
        rNode.parentNode.removeChild(rNode);
        break;
      case REPLACE:
        const newNode =
          p.newNode instanceof Element
            ? render(p.newNode)
            : document.createTextNode(p.newNode);
        rNode.parentNode.replaceChild(newNode, rNode);
        break;
      default:
        break;
    }
  });
}
export default doPatch;
